package com.gcloud.mesh.asset.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.SysLogOperateType;
import org.jeecg.common.constant.enums.SysLogType;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.gcloud.framework.db.PageResult;
import com.gcloud.mesh.asset.entity.CloudResourceEntity;
import com.gcloud.mesh.asset.service.ICloudResourceService;
import com.gcloud.mesh.dcs.annotation.ParamSecurity;
import com.gcloud.mesh.header.msg.BaseReplyMsg;
import com.gcloud.mesh.header.msg.asset.CreateCloudResourceMsg;
import com.gcloud.mesh.header.msg.asset.PageCloudResourceMsg;
import com.gcloud.mesh.header.msg.asset.UpdateCloudResourceMsg;
import com.gcloud.mesh.header.vo.asset.CloudResourceAnalysisVo;
import com.gcloud.mesh.header.vo.asset.CloudResourceItemVo;

import cn.hutool.core.lang.UUID;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(tags = "云资源管理")
@RestController
@RequestMapping("/cloud_resource")
@Slf4j
public class CloudResourceController {

	@Autowired
	private ICloudResourceService cloudResourceService;
	
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	
	private static final String HEADER_TOKEN = "X-Access-Token";
	
	//处理Mass Assignment: Insecure Binder Configuration
	@InitBinder
	public void populateCustomerRequest(WebDataBinder binder) {
	    binder.setDisallowedFields(new String[]{});
	}
	
	// @AutoLog(value = "查看云资源列表", operateType = CommonConstant.OPERATE_TYPE_LIST)
	@ApiOperation(value = "查询云资源分页", notes = "云资源分页")
	@RequestMapping(value = "/page", method = RequestMethod.POST)
	@RequiresPermissions(value = { "cloud_resourcePage" })
	@ParamSecurity(enabled = true)
	public PageResult<CloudResourceItemVo> page(@Valid PageCloudResourceMsg msg) throws Exception {
		PageResult<CloudResourceItemVo> result = cloudResourceService.page(msg);
        if(msg.getTitle() != null) {
			if(msg.getTitle().contains("多数据中心调度-数据跨层感知与智能分析-L3层：云平台资源")) {
				if(msg.getType().equals(0)) {
					sysBaseAPI.addLog(msg.getContent() != null?msg.getContent():"查询云平台资源列表" , SysLogType.OPERATE, SysLogOperateType.DETAIL, null, null, msg.getTitle() != null ? msg.getTitle(): "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L3层：云平台资源");
				}
			}else {
				sysBaseAPI.addLog(msg.getContent() != null?msg.getContent():"查询云平台资源列表" , SysLogType.OPERATE, SysLogOperateType.QUERY, null, null, msg.getTitle() != null ? msg.getTitle(): "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L3层：云平台资源");
			}
		}
		return result;
	}

	// @AutoLog(value = "新增云资源", operateType = CommonConstant.OPERATE_TYPE_ADD)
	@ApiOperation(value = "新增云平台资源", notes = "新增云资源")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	@RequiresPermissions(value = { "cloud_resourceCreate" })
	@ParamSecurity(enabled = true)
	public BaseReplyMsg create(@RequestBody CreateCloudResourceMsg msg, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = cloudResourceService.create(msg, getUser(request, response), request, response);
//		StringBuffer buff = new StringBuffer();
//    	buff.append("新增云平台资源；ID：" + id+msg.toString());
//    	// buff.append("，"+msg.toString());
//		sysBaseAPI.addLog(buff.toString(), SysLogType.OPERATE, SysLogOperateType.ADD, null, null, "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L3层：云平台资源");
		// sysBaseAPI.addLog("新增云资源；ID:" + id, null, CommonConstant.OPERATE_TYPE_ADD);
		BaseReplyMsg reply = new BaseReplyMsg();
		reply.setData(id);
		return reply;
	}

	//@AutoLog(value = "删除云资源", operateType = CommonConstant.OPERATE_TYPE_DELETE)
	@ApiOperation(value = "删除云资源", notes = "删除云资源")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@RequiresPermissions(value = { "cloud_resourceDelete" })
	@ParamSecurity(enabled = true)
	public void delete(String id) throws Exception {
		CloudResourceEntity cloud = cloudResourceService.delete(id);
		sysBaseAPI.addLog("删除云平台资源；ID:" + id+"，云平台资源名称："+cloud.getName(),SysLogType.OPERATE, SysLogOperateType.DELETE, null, null, "精确管控与供电制冷联动-基础资源细粒度感知-资源管理L3层-云平台资源");
	}

	//@AutoLog(value = "云资源详情", operateType = CommonConstant.OPERATE_TYPE_DETAIL)
	@ApiOperation(value = "云资源详情", notes = "云资源详情")
	@RequestMapping(value = "/detail", method = RequestMethod.POST)
	// @RequiresPermissions(value = {"cloud_resourceDetail"})
	@ParamSecurity(enabled = true)
	public CloudResourceItemVo detail(String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
		//sysBaseAPI.addLog("云资源详情；ID:" + id, null, CommonConstant.OPERATE_TYPE_DETAIL);
		sysBaseAPI.addLog("查看云平台资源详情；ID:" + id, SysLogType.OPERATE, SysLogOperateType.DETAIL, null, null, "精确管控与供电制冷联动-基础资源细粒度感知-资源管理L3层-云平台资源");
		return cloudResourceService.detail(id, getUser(request, response), request, response);
	}

	@ApiOperation(value = "虚拟机详情", notes = "虚拟机详情")
	@RequestMapping(value = "/vm_detail", method = RequestMethod.POST)
	@ParamSecurity(enabled = true)
	public CloudResourceItemVo vmDetail(String id) throws Exception {
		sysBaseAPI.addLog("查看虚拟机详情；ID:" + id, null, CommonConstant.OPERATE_TYPE_DETAIL);
		return cloudResourceService.detail(id);
	}

	@ApiOperation(value = "查看容器详情", notes = "容器详情")
	@RequestMapping(value = "/k8s_detail", method = RequestMethod.POST)
	@ParamSecurity(enabled = true)
	public CloudResourceItemVo k8sDetail(String id) throws Exception {
		sysBaseAPI.addLog("查看容器详情；ID:" + id, null, CommonConstant.OPERATE_TYPE_DETAIL);
		return cloudResourceService.detail(id);
	}

	// @AutoLog(value = "更新云资源", operateType = CommonConstant.OPERATE_TYPE_UPDATE)
	@ApiOperation(value = "更新云资源", notes = "更新云资源")
	@RequestMapping(value = "/update1", method = RequestMethod.POST)
	@RequiresPermissions(value = { "cloud_resourceUpdate" })
	@ParamSecurity(enabled = true)
	public void update(@Valid UpdateCloudResourceMsg msg) throws Exception {
		cloudResourceService.update(msg);
		StringBuffer buff = new StringBuffer();
    	buff.append("更新云平台资源；ID：" + msg.getId());
    	buff.append("，"+"云资源名称："+msg.getName() == null?"无":msg.getName());
		sysBaseAPI.addLog(buff.toString(), SysLogType.OPERATE, SysLogOperateType.UPDATE, null, null, "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L3层：云平台资源");
	}

	// @AutoLog(value = "云平台资源同步", operateType = CommonConstant.OPERATE_TYPE_SYNC, module="精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L3层：云平台资源")
	@ApiOperation(value = "云资源同步", notes = "云资源同步")
	@RequestMapping(value = "/sync", method = RequestMethod.GET)
	// @RequiresPermissions(value = {"cloud_resourceSync"})
	@ParamSecurity(enabled = true)
	public BaseReplyMsg sync() throws Exception {
		BaseReplyMsg reply = new BaseReplyMsg();
		String res = cloudResourceService.sync();
		sysBaseAPI.addLog("云平台资源同步"+"("+res+")", SysLogType.OPERATE, SysLogOperateType.SYNC, null, null, "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L3层：云平台资源");
		reply.setData(res);
		return reply;
	}

	@AutoLog(value = "查看云平台资源分析", operateType = CommonConstant.OPERATE_TYPE_DETAIL)
	@ApiOperation(value = "云资源分析", notes = "云资源分析")
	@RequestMapping(value = "/analysis", method = RequestMethod.GET)
	@RequiresPermissions(value = { "cloud_resourceAnalysis" })
	@ParamSecurity(enabled = true)
	public CloudResourceAnalysisVo analysis() throws Exception {
		return cloudResourceService.analysis();
	}
	
    private String getUser(HttpServletRequest request, HttpServletResponse response) {
    	String token = request.getHeader(HEADER_TOKEN);  	
    	String userId = null;
    	try {
    		String username = JwtUtil.getUsername(token);
    		LoginUser sysUser = sysBaseAPI.getUserByName(username);
    		userId = sysUser.getId();
    	} catch(Exception e) {
    		log.error("[SM][AssetController][getUser] 获取用户异常：{}", e.getMessage());
    	}	
		return userId;
    }

}
